$(document).ready(
    function(){
        
        function setRatingStars(rating){
            var rating = Number(rating);
            $("#rating").attr("title", rating + " / 5");
            var html = "";
            var counter = 1;
            while(counter <= 5){
                if(rating >= counter){
                    html += "<img id='star" + counter + "' class='rating-star' src='../resources/images/rating-star.png'>";
                } else {
                    html += "<img id='star" + counter + "' src='../resources/images/rating-star.png' class='grayscale rating-star'>";
                }
                counter++;
            }
            $("#rating").html(html);
            Controller.init();
        }
        
        function showComments(comments){
            $("#comments-posted").html("");
            for(var c in comments){
                var c = comments[c];
                var html = "<div class='bar-comment-user'><img class='person-head' src='../resources/images/personhead.svg'>" + c.first_name + " " + c.last_name + "<span style='font-size: 16px;'><img class='calendar-icon' src='../resources/images/calendar.svg'>" + c.date + " " + c.time + "</span></div>";
                html += "<div class='bar-comment'><span style='padding: 5px'>" + c.comment + "</span></div>";
                $("#comments-posted").append(html);
            }
        }
        
        /*https://developers.google.com/maps/documentation/javascript/geocoding*/
        /*https://developers.google.com/maps/documentation/javascript/tutorial*/
                
        function getUserPos(){
            var dfd = new $.Deferred();
            var userPos = null;
            
            if(navigator.geolocation){
                navigator.geolocation.getCurrentPosition(
                    function(position){
                        userPos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                        dfd.resolve(userPos);
                    }
                );
            } else{
                dfd.resolve(userPos);
            }
            
            return dfd.promise();
        }
        
        function initialize(args) {
            
            $.when(getUserPos()).then(
                function(userItems){
            
                    var latLng = args.latlong.substring(1,args.latlong.length-1).split(",");
                    var latLong = {
                        lat: Number(latLng[0]),
                        lng: Number(latLng[1])
                    };
                    
                    latLong = new google.maps.LatLng(latLong.lat, latLong.lng);
                    
                    var mapOptions = {
                        center: latLong,
                        zoom: 16
                    };
                    
                    var map = new google.maps.Map(document.getElementById('map-canvas'),
                        mapOptions);
                                        
                    var barMarker = new google.maps.Marker({
                        position: latLong,
                        map: map,
                        title: args.name
//                        icon: "../resources/images/beermarker.png"
                    });
                    
                    if(userItems){
                        var userMarker = new google.maps.Marker({
                            position: userItems,
                            map: map,
                            title: "Din posisjon"
                            //,icon: image
                        });
                        
                        var rad = function(x) {
                            return x * Math.PI / 180;
                        };

                        var getDistance = function(p1, p2) {
                            var R = 6378137; // Earth’s mean radius in meter
                            var dLat = rad(p2.lat() - p1.lat());
                            var dLong = rad(p2.lng() - p1.lng());
                            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                              Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
                              Math.sin(dLong / 2) * Math.sin(dLong / 2);
                            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                            var d = R * c;
                            return d; // returns the distance in meter
                        };
                        
                        var distance = getDistance(latLong, userItems)/1000;
                        
                        if(distance < 5){
                            var directionsDisplay = new google.maps.DirectionsRenderer();
                            var directionsService = new google.maps.DirectionsService();
                            var start = userItems;
                            var end = latLong;
                            var request = {
                                origin: start,
                                destination: end,
                                travelMode: google.maps.TravelMode.WALKING
                            };
                            directionsService.route(request, function(response, status){
                                if(status === google.maps.DirectionsStatus.OK){
                                    directionsDisplay.setDirections(response);
                                    directionsDisplay.setMap(map);
                                    directionsDisplay.setOptions({suppressMarkers: true});
                                }
                            });
                        }
                    }
                    
                    var barContentString = "<div class='marker-info'>" + args.name + "</div>";
                
                    var userContentString = "<div class='marker-info'>Din posisjon.</div>";

                    var barInfoWindow = new google.maps.InfoWindow({
                        content: barContentString
                    });
                    
                    var userInfoWindow = new google.maps.InfoWindow({
                        content: userContentString
                    });
                    
                    google.maps.event.addListener(barMarker, 'click', function() {
                        barInfoWindow.open(map, barMarker);
                    });
                    
                    google.maps.event.addListener(userMarker, 'click', function() {
                        userInfoWindow.open(map, userMarker);
                    });
                }
            );
        }
        //google.maps.event.addDomListener(window, 'load', initialize);
        
        var UI = {};
        (function (UI) {
            
            UI.start = function(){
                Controller.init();
                
                var barId = getURLparam("barid");
                var bar = {};
                var dfd = new $.Deferred();
                var args = {
                    action : 'Select',
                    barid : barId
                };
                $.when(Actions.getBarProfile(args)).then(
                    function(returnItems){
                        bar = returnItems;
                        $("#barname").html(returnItems.name);
                        $("#bardescription").html(returnItems.description);
                        $("#baraddress").html(returnItems.address);
                        $("#postalno").html(returnItems.postal_no);
                        $("#place").html(returnItems.place);
                        $("#status").html(returnItems.status);
                        $("#firstname").html(returnItems.owner_first_name);
                        $("#lastname").html(returnItems.owner_last_name);
                        if(returnItems.image !== "") $("#profileimg").attr("src", "data:" + returnItems.image_type + ";base64," + returnItems.image);
                        setStatusColor(returnItems.status_id);
                        if(returnItems.facebook_user === ''){
                            $("#facebook-link").attr("href", null);
                            $("#facebook-link").attr("title", 'Facebook er ikke registrert for ' + returnItems.name);
                            $("#facebook-link").css('opacity', '0.4');
                        } else{
                            $("#facebook-link").attr("href", $("#facebook-link").attr("href") + returnItems.facebook_user);
                            $("#facebook-link").attr("title", returnItems.name + " på Facebook");
                        }
                        if(returnItems.twitter_user === ''){
                            $("#twitter-link").attr("href", null);
                            $("#twitter-link").attr("title", 'Twitter er ikke registrert for ' + returnItems.name);
                            $("#twitter-link").css('opacity', '0.4');
                        } else{
                            $("#twitter-link").attr("href", $("#twitter-link").attr("href") + returnItems.twitter_user);
                            $("#twitter-link").attr("title", returnItems.name + " på Twitter");
                        }
                        if(returnItems.instagram_user === ''){
                           $("#instagram-link").attr("href", null);
                            $("#instagram-link").attr("title", 'Instagram er ikke registrert for ' + returnItems.name);
                            $("#instagram-link").css('opacity', '0.4');
                        } else{
                            $("#instagram-link").attr("href", $("#instagram-link").attr("href") + returnItems.instagram_user);
                            $("#instagram-link").attr("title", returnItems.name + " på Instagram");
                        }
                        if(returnItems.spotify_user === ''){
                            $("#spotify-link").attr("href", null);
                            $("#spotify-link").attr("title", 'Spotify er ikke registrert for ' + returnItems.name);
                            $("#spotify-link").css('opacity', '0.4');
                        } else{
                            $("#spotify-link").attr("href", $("#spotify-link").attr("href") + 'user/' + returnItems.spotify_user);
                            $("#spotify-link").attr("title", returnItems.name + " på Spotify");
                        }
                        $("#hashtag").html("#" + returnItems.hashtag);
                        $("#homepage").attr("href", returnItems.homepage);
                        $("#map-link").attr("href", "https://www.google.no/maps/place/" + returnItems.address + ",+" + returnItems.postal_no + "+" + returnItems.place + "/");
                        
                        initialize(bar);
                        
                        $.when(Actions.getAvgRatingBar(args), Actions.getBarComments(args), Actions.getBarTags(args)).then(
                            function(ratingItems, comments, tags){
                                setRatingStars(ratingItems.rating);
                                
//                                for(var c in comments){
//                                    var c = comments[c];
//                                    var html = "<div class='bar-comment-user'><img class='person-head' src='../resources/images/personhead.svg'>" + c.first_name + " " + c.last_name + "<span style='font-size: 16px;'><img class='calendar-icon' src='../resources/images/calendar.svg'>" + c.date + " " + c.time + "</span></div>"
//                                    html += "<div class='bar-comment'><span style='padding: 5px'>" + c.comment + "</span></div>"
//                                    $("#comments-posted").append(html);
//                                }
                                showComments(comments);
                                
                                var tagCounter = 0;
                                for(var t in tags){
                                    var t = tags[t];
                                    tagCounter++;
                                    if(tagCounter <=5){
                                        var html = "<div class='bar-tag'>" + t.name + "</div>";
                                        $("#bar-tags-area").append(html);
                                    } else{
                                        if(tagCounter === 6){
                                            var html = "<div id='bar-tag-show-all'><a> Vis Alle <img src='../resources/images/arrow_down.svg' style='height: 12px; width: 12px'> </a></div>";
                                            $("#bar-tags-area").append(html);
                                        }
                                        var html = "<div class='bar-tag hidden'>" + t.name + "</div>";
                                        $("#bar-tags-area").append(html);
                                    }
                                    
                                }
                                
                                dfd.resolve();
                            }
                        );
                        
                        var feed = new Instafeed({
                            get: 'tagged',
                            tagName: returnItems.hashtag || "awesome",
                            limit: 10,
                            clientId: '585eb09087af49048cf6d755ab2c6e98'
                        });
                        feed.run();
                        $("#hashtag").text("#barviking");

                    }
                );
                    return dfd.promise();
            };
            
            function setStatusColor(status_id){
                switch(status_id){
                    case '1':
                        $("#status").css("color", "green");
                        break;
                    case '2':
                        $("#status").css("color", "red");
                        break;
                    case '3':
                        $("#status").css("color", "orange");
                        break;
                    case '4':
                        $("#status").css("color", "blue");
                        break;
                }
            }
            
        }(UI));
        var Helpers = {};
        (function (Helpers) {
            
            
        }(Helpers));
        
        var Actions = {};
        (function (Actions) {
            
            Actions.getBarProfile = function(args) {
                var dfd = new $.Deferred();
                console.log("%c runSQL getBarProfile", "color: green");
                $.ajax({
                    type: "POST",
                    url: "../resources/helpers/getBarProfile.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        console.log("%c Returned from getBarProfile:","color: green");
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getAvgRatingBar = function(args) {
                var dfd = new $.Deferred();
                console.log("%c runSQL getBarProfile", "color: green");
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getAvgRatingBar.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        console.log("%c Returned from getAvgRatingBar:","color: green");
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getPrivateuserId = function(args) {
                var dfd = new $.Deferred();
                console.log("%c runSQL getPrivateuserId", "color: green");
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getPrivateuserId.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getBarComments = function(args) {
                var dfd = new $.Deferred();
                console.log("%c runSQL getBarComments", "color: green");
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getBarComments.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.getBarTags = function(args) {
                var dfd = new $.Deferred();
                console.log("%c runSQL getBaTags", "color: green");
                $.ajax({
                    type: "GET",
                    url: "../resources/helpers/getBarTags.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        data = JSON.parse(data);
                        dfd.resolve(data);
                    }
                });
                return dfd.promise();
            };
            
            Actions.setBarRating = function(args) {
                var dfd = new $.Deferred();
                console.log("%c runSQL setBarRating", "color: green");
                $.ajax({
                    type: "POST",
                    url: "../resources/helpers/setBarRating.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        dfd.resolve();
                    }
                });
                return dfd.promise();
            };
            
            Actions.setBarComment = function(args) {
                var dfd = new $.Deferred();
                console.log("%c runSQL setBarComment", "color: green");
                $.ajax({
                    type: "POST",
                    url: "../resources/helpers/setBarComment.php",
                    data: args,
                    cache: false,
                    success: function(data){
                        dfd.resolve();
                    }
                });
                return dfd.promise();
            };
        }(Actions));
        
        var Controller = {};
        (function (Controller) {
            
            var ratingStarClicked = function(val){
                $.when(Actions.getPrivateuserId({action: 'get'})).then(
                    function(ret){
                        var args = {
                            action: 'get',
                            value : val.value,
                            userid : ret.user_id,
                            barid: getURLparam("barid")
                        };
                        $.when(Actions.setBarRating(args)).then(
                            function(){
                                var starArgs = {
                                    action: 'Select',
                                    barid: getURLparam("barid")
                                };
                                $.when(Actions.getAvgRatingBar(starArgs)).then(
                                    function(ret){
                                        setRatingStars(ret.rating);
                                    }
                                );
                            }
                        );
                    }
                );
            };
            
            var commentSubmitted = function(){
                var userArgs = {
                    action: 'get'
                }
                var comment = $("#new-comment").val().replace(/</g, "&lt;").replace(/>/g, "&gt;"); /*Avoid html injection*/
                $.when(Actions.getPrivateuserId(userArgs)).then(
                    function(ret){
                        var args = {
                            action: 'set',
                            userid: ret.user_id,
                            barid: getURLparam("barid"),
                            comment: comment
                        };
                        $.when(Actions.setBarComment(args)).then(
                            function(){
                                var commentArgs = {
                                    action: "get",
                                    barId: getURLparam("barid")
                                };
                                $.when(Actions.getBarComments(commentArgs)).then(
                                    function(comments){
                                        showComments(comments);
                                        $("#new-comment").val("");
                                    }
                                );
                            }
                        );
                    }
                );
            };
            
            var showAllTags = function(){
                var tags = $('#bar-tags-area').children('.hidden');
                
                $('#bar-tag-show-all').slideUp('fast', function(){
                    $('#bar-tag-show-all').css('display', 'none');
                    tags.slideDown('fast', function(){
                        tags.removeClass('hidden');
                    });                                     
                });
            };
            
            Controller.init= function(){
                $("#star1").unbind("click").bind("click", function(){ var args = {value : 1}; ratingStarClicked(args);});
                $("#star2").unbind("click").bind("click", function(){ var args = {value : 2}; ratingStarClicked(args);});
                $("#star3").unbind("click").bind("click", function(){ var args = {value : 3}; ratingStarClicked(args);});
                $("#star4").unbind("click").bind("click", function(){ var args = {value : 4}; ratingStarClicked(args);});
                $("#star5").unbind("click").bind("click", function(){ var args = {value : 5}; ratingStarClicked(args);});
                $("#submit-comment").unbind("click").bind("click", function(){ commentSubmitted();});
                $("#bar-tag-show-all").unbind("click").bind("click", function(){ showAllTags();});
            };
            
        }(Controller));	
        
        $.when(UI.start()).then(
            function(){
                Controller.init();
            }
        );
    }
);